package jam4j;

import java.text.AttributedCharacterIterator;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * The date format used by the original Perforce Jam, faithfully reproduced
 * here.
 * 
 * @author Luke Maurer
 */
public class JamDateFormat extends SimpleDateFormat {
    private static final String PATTERN_TWO_DIGITS =
        "EEE MMM d HH:mm:ss yyyy";
    private static final String PATTERN_ONE_DIGIT =
        "EEE MMM  d HH:mm:ss yyyy";

    public JamDateFormat() {
        super(PATTERN_TWO_DIGITS);
    }
    
    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo,
            FieldPosition pos) {
        final boolean switched = selectPattern(date);
        try {
            return super.format(date, toAppendTo, pos);
        } finally {
            if (switched)
                applyPattern(PATTERN_TWO_DIGITS);
        }
    }

    @Override
    public AttributedCharacterIterator formatToCharacterIterator(
            Object object) {
        final boolean switched;
        
        if (object instanceof Date)
            switched = selectPattern((Date) object);
        else if (object instanceof Number)
            switched = selectPattern(new Date(((Number) object).longValue()));
        else
            switched = false;
        
        try {
            return super.formatToCharacterIterator(object);
        } finally {
            if (switched)
                applyPattern(PATTERN_TWO_DIGITS);
        }
    }
    
    private boolean selectPattern(Date date) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        
        final boolean switched = calendar.get(Calendar.DAY_OF_MONTH) < 10;
        
        applyPattern(
                switched ? PATTERN_ONE_DIGIT : PATTERN_TWO_DIGITS);
        
        return switched;
    }
}